<template>
  <el-card shadow="never">
    <el-card class="card-form" shadow="never">
      <div slot="header" class="clearfix">
        <el-button @click="closeForm">取消</el-button>
        <el-button @click="submit" type="primary">保存</el-button>
      </div>
      <div>
        <el-form size="mini" ref="form" :model="form" :rules="rules" :label-position=labelPosition label-width="120px">
          <el-form-item label="分组名称" prop="group_name" required>
            <el-input style="width:198px" v-model="form.group_name" clearable></el-input>
          </el-form-item>
          <el-form-item label="接口名称" prop="api_name" required>
            <el-input style="width:198px" v-model="form.api_name" clearable></el-input>
          </el-form-item>
          <el-form size="mini" ref="form.data" :model="form.data" :rules="rules" :label-position=labelPosition
                   label-width="120px">
            <el-form-item label="请求地址" prop="url" required>
              <el-autocomplete
                  v-model="form.data.url"
                  :fetch-suggestions="queryUrls"
                  placeholder="空值即为不处理"
                  @select="handleSelect"
                  style="width: 80%"
              ></el-autocomplete>
            </el-form-item>
            <el-form-item label="请求方式" prop="method" required>
              <el-select v-model="form.data.method" filterable placeholder="请选择">
                <el-option
                    v-for="item in method"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="Content-Type">
              <el-select v-model="form.data['Content-Type']" filterable placeholder="请选择">
                <el-option
                    v-for="item in content_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="请求体">
              <el-input v-model="form.data.body" type="textarea" :rows=2 placeholder="请求体"></el-input>
            </el-form-item>
          </el-form>
          <el-form-item label="接口描述">
            <el-input v-model="form.description" type="textarea" :rows=2 placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-collapse>
            <el-collapse-item title="argument" name="argument">
              <el-card shadow="never">
                <el-form-item>
                  <el-button @click="addArgument" icon="el-icon-plus" style="float: right"></el-button>
                </el-form-item>
                <el-form-item label-width="100px" v-for="(arg, index) in form.data.argument" :key="arg.index">
                  <el-collapse-item :title="arg.argument_type+'：'+arg.key+'： '+arg.argument_opinion" :name="arg.index">
                    <el-form-item label="key">
                      <el-input v-model="arg.key" placeholder="参数名" style="width: 200px"></el-input>
                      <el-select v-model="arg['argument_type']" filterable placeholder="参数类型">
                        <el-option
                            v-for="item in argument_type"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled">
                        </el-option>
                      </el-select>
                      <el-select v-model="arg['argument_opinion']" filterable placeholder="取参规则">
                        <el-option
                            v-for="item in argument_opinion"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            :disabled="item.disabled">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="value">
                      <el-input placeholder="默认值" v-model="arg.value"></el-input>
                    </el-form-item>
                    <el-form-item label="function">
                      <el-autocomplete
                          v-model="arg.function.function_name"
                          :fetch-suggestions="queryTools"
                          placeholder="方法名"
                          @select="handleSelect"
                      ></el-autocomplete>
                      <el-input style="width: 250px" v-if="arg.function.function_name!==''" placeholder="请遵照提示填写,以免出现问题"
                                v-model="arg.function.parameter"></el-input>
                    </el-form-item>
                    <el-form-item label="description">
                      <el-input v-model="arg.description"></el-input>
                    </el-form-item>
                    <el-form-item style="float: right">
                      <el-button icon="el-icon-delete" @click="removeArgument(index)"></el-button>
                    </el-form-item>
                  </el-collapse-item>
                </el-form-item>
              </el-card>
            </el-collapse-item>
          </el-collapse>
          <br>
          <el-form-item label="请求前处理">
            <el-autocomplete
                v-model="form.request_function.function_name"
                :fetch-suggestions="queryLeaves"
                placeholder="空值即为不处理"
                @select="handleSelect"
            ></el-autocomplete>
            <el-input v-model="form.request_function.parameter" placeholder="请按照提示填写" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="请求后处理">
            <el-autocomplete
                v-model="form.response_function.function_name"
                :fetch-suggestions="queryReturns"
                placeholder="空值即为不处理"
                @select="handleSelect"
            ></el-autocomplete>
            <el-input v-model="form.response_function.parameter" placeholder="请按照提示填写" style="width: 400px"></el-input>
          </el-form-item>
          <el-collapse>
            <el-collapse-item title="format" name="format">
              <el-card shadow="never">
                <el-form-item>
                  <el-button @click="addFormat" icon="el-icon-plus" style="float: right"></el-button>
                </el-form-item>
                <el-form-item label-width="100px" v-for="(fmt, index) in form.format" :key="fmt.key">
                  <el-collapse-item width :title="fmt.condition + ' ' + fmt['cache_open']" :name="fmt.key">
                    <el-form-item label="condition">
                      <el-input v-model="fmt.condition" placeholder="$.key!=value | !exit$.key"></el-input>
                    </el-form-item>
                    <el-form-item label="template">
                      <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8}" placeholder="默认值"
                                v-model="fmt.template"></el-input>
                    </el-form-item>
                    <el-form-item style="float: right">
                      <el-switch
                          active-color="#13ce66"
                          inactive-color="#ff4949"
                          v-model="fmt['cache_open']">
                      </el-switch>
                      <el-button icon="el-icon-delete" @click="removeFormat(index)"></el-button>
                    </el-form-item>
                  </el-collapse-item>
                </el-form-item>
              </el-card>
            </el-collapse-item>
          </el-collapse>
          <br>
          <el-form-item label="缓存配置">
            <el-input style="width:198px" placeholder="主键" v-model="form.cache.key"></el-input>
            <el-input style="width:198px" placeholder="时长(s)" type="number" v-model.number="form.cache.hold"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="card-json" shadow="never">
      <div slot="header" class="clearfix">
        <el-button type="primary" disabled>复制</el-button>
      </div>
      <json-viewer :value="form" :expand-depth=3 copyable></json-viewer>
    </el-card>
  </el-card>
</template>

<script>
import JsonViewer from 'vue-json-viewer'
import utils from "../../assets/js/utils";
import {submitHandler} from "../../assets/js/designer"

export default {
  name: "designer-form",
  created() {
  },
  mounted() {
    this.loadTools();
    this.loadLeaves();
    this.loadReturns();
    this.loadUrls()
  },
  components: {
    JsonViewer
  },
  props: {
    form: {}
  },
  data() {
    return {
      labelPosition: 'right',
      rules: {
        group_name: [
          {min: 3, max: 20, message: '分组名称在3 到 20 个字符之间', trigger: 'blur'}
        ],
        api_name: [
          {min: 3, max: 20, message: '接口名称在3 到 20 个字符之间', trigger: 'blur'}
        ],
        url: [
          {required: true, message: '地址不能为空', trigger: 'blur'},
        ],
        method: [
          {required: true, message: 'method不能为空', trigger: 'blur'}
        ]
      },
      method: utils.options.method,
      content_type: utils.options.content_type,
      argument_type: utils.options.argument_type,
      argument_opinion: utils.options.argument_opinion,
      value_type: utils.options.value_type,
      net: utils.options.net,
      _net: '',
      tools: [],
      leaves: [],
      returns: [],
      urls: [],
      state: '',
      timeout: null
    }
  },
  methods: {
    closeForm: function () {
      this.$emit("listenToChildEvent", this.formDialogVisible);
    },
    addArgument: function () {
      let argument = this.form.data.argument
      let key = 'undefined' + argument.length
      let argumentType = 'undefined' + argument.length
      this.form.data.argument.push(
          {
            key: key,
            value: "",
            argument_type: argumentType,
            function: {
              function_name: "",
              parameter: "",
              value_type: "",
            },
            description: "",
          }
      )
    },
    removeArgument: function (index) {
      console.log(index)
      if (index !== -1) {
        this.form.data.argument.splice(index, 1)
      }
    },
    addFormat: function () {
      let format = this.form.format
      let condition = 'undefined' + format.length
      let cache_open = false
      this.form.format.push({
        condition: condition,
        template: "",
        cache_open: cache_open,
      })
    },
    removeFormat: function (index) {
      if (index !== -1) {
        this.form.format.splice(index, 1)
      }
    },
    submit: function () {
      submitHandler(this)
    },
    loadTools() {
      utils.selector('query', 'tool').then(res => {
        if (res.data.code === 0) {
          this.tools = res.data.result
        }
      })
    },
    loadLeaves() {
      utils.selector('query', 'request').then(res => {
        if (res.data.code === 0) {
          this.leaves = res.data.result
        }
      })
    },
    loadReturns() {
      utils.selector('query', 'response').then(res => {
        if (res.data.code === 0) {
          this.returns = res.data.result
        }
      })
    },
    loadUrls() {
      utils.selector('query', 'url').then(res => {
        if (res.data.code === 0) {
          this.urls = res.data.result
        }
      })
    },
    queryTools(queryString, cb) {
      let restaurants = this.tools;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    queryLeaves(queryString, cb) {
      let restaurants = this.leaves;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    queryReturns(queryString, cb) {
      let restaurants = this.returns;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    queryUrls(queryString, cb) {
      let restaurants = this.urls;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      this.$notify({
        title: item.value,
        message: item.description,
        duration: 5000
      });
    }
  },

}
</script>

<style scoped>
.card-json {
  width: 29%;
  float: right;
}

.card-form {
  width: 70%;
  float: left;
}
</style>
